﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace IpProxyLibrary
{
    /// <summary>
    /// 特性：指定属性的排序和是否出现在缓存中使用
    /// </summary>
    public class CacheOrderAttribute : Attribute
    {
        public string Name { get; set; }
    }

    /// <summary>
    /// 文件缓存共有类
    /// </summary>
    public class FileCache
    {
        private static FileCache instance = new FileCache();

        private FileCache() { }

        public static FileCache getInstance()
        {
            return instance;
        }

        public void save<T>(T obj) where T : CacheBean
        {
            writeFile<T>(Json.getJsonByObject(obj));
        }

        public T load<T>() where T : CacheBean
        {
            string fileText = loadFile<T>();
            return Json.getObjectByJson<T>(fileText);
        }

        private void writeFile<T>(string text) where T : CacheBean
        {
            string cachePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "cache", typeof(T).Name.ToString() + ".txt");
            using (FileStream fsWrite = new FileStream(cachePath, FileMode.OpenOrCreate, FileAccess.Write))
            {
                byte[] buffer = Encoding.Default.GetBytes(text);
                fsWrite.Write(buffer, 0, buffer.Length);
            }
        }

        private String loadFile<T>() where T : CacheBean
        {
            string cachePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "cache", typeof(T).Name.ToString() + ".txt");
            using (FileStream fsWrite = new FileStream(cachePath, FileMode.OpenOrCreate, FileAccess.Read))
            {
                byte[] buffer = new byte[1024];
                int size = 0;
                string result = "";
                while ((size = fsWrite.Read(buffer, 0, buffer.Length))>0)
                {
                    result += Encoding.Default.GetString(buffer, 0, size);
                }
                return result;
            }
        }
    }
}
